package com.example.bishe.demos.web;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public String up(String nickname, MultipartFile photo, HttpServletRequest request) throws IOException//昵称，头像
    {
        System.out.println(nickname);//获取图片的原始名称
        System.out.println(photo.getOriginalFilename());//取文件类型
        System.out.println(photo.getContentType());
//    System.out.println(System.getProperty("user.dir"));  用不到

        String path = request.getServletContext().getRealPath("/upload/");//请求发送的上下文，可以获得相应的路径，即web服务器的运行目录（动态获取）
        System.out.println(path);
        saveFile(photo, path);
        return"上传成功 ";
    }
    public void saveFile(MultipartFile photo,String path)throws IOException{
        //判断创建的目录是否存在，如果不存在则创建
        File dir = new File(path);
        if(!dir.exists()){
            //创建目录
           dir.mkdir();
    }
        File file = new File(path+photo.getOriginalFilename());
        photo.transferTo(file);
    }

}

